/* 
    公共Table封装
 */
import React from 'react'
import propTypes from 'prop-types'
import Utils from '../../utils/utils'
import {Table, Button,} from 'antd'
import  "./index.css"
class ETable extends React.Component {
    // props类型校验和声明
    static propTypes = {
        showIndex: propTypes.bool,//是否显示序列号
        pagination: propTypes.object,//分页设置，Utils.pagination
        updateSelectedItem: propTypes.func,//选择回调，Utils.updateSelectedItem
        columns: propTypes.array,//每列内容设置
        dataSource: propTypes.array,//数据源
        scroll: propTypes.object,//滚动宽高设置
        rowSelection: propTypes.string,//默认radio单选，可选checkbox多选
        noPagin: propTypes.bool,//默认false 分页
        otherHeight:propTypes.number,//头尾部除表格外占得高度
        selectedKey:propTypes.string,//勾选item的ID值名字，默认id

        selectedIds: propTypes.array,//默认勾选数据源，暂无实现功能
    }
    // props默认参数
    static defaultProps = {
        showIndex: false,
        noPagin: false,
        dataSource:[],
        otherHeight:390,
        selectedKey:'id',
    }
    constructor(props){
        super(props)
        this.state = {
        }
    }

    scrollWidth = 0;
    componentWillUnmount(){
        this.setState = (state,callback)=>{
            return;
          };
    }

    componentDidMount() {
        this.setData(this.props)
    }

    componentWillReceiveProps(nextProps){
        if (nextProps.dataSource && this.props.dataSource && !Utils.isEqual(nextProps.dataSource,this.props.dataSource)) {
            this.setData(nextProps)
        }
    }

    setData = (props)=>{
        this.onSelectCallBack([],{},[]);//数据源改变时清空选择
        if (props.pagination) {
            this.setState({
                pageNo :props.pagination.current 
            })
        }
        if(props.showIndex){
            let indexCol = {
                title:'序号',
                dataIndex:'index',
                width:70,
                key:'index',
                fixed:'left',
                sorter: (a, b) => Number(b.key) - Number(a.key),
                render: (text, item, index) => {
                    let number = 0
                    if(item.key!==null) number = item.key+1
                    return (
                        <div>{number}</div>
                    )
                    
                }
            }
            let columns = props.columns;
            if (columns.length>0 && columns[0].title !== '序号') {
                columns.unshift(indexCol);
            }
            let scroll = props.scroll;
            scroll.x += indexCol.width;
            if(this.scrollWidth === 0) this.scrollWidth = scroll.x;
            this.height = Math.max(this.height,document.body.offsetHeight);
            scroll.y = this.height - this.props.otherHeight - 30;
            this.setState({
                columns,
                scroll,
                dataSource:props.dataSource
            },()=>{
                this.initColumns=columns;
                this.initScroll=scroll;
            });
        }
    }

    height = 0;
    //处理行点击事件
    onRowClick = (record, index) => {
        let pageNo = this.state.pageNo - 1;
        let pageSize = 0;
        let props = this.props
        if (!this.props.noPagin) {
            if(!props.pagination) return;
            pageSize =  props.pagination.pageSize ? props.pagination.pageSize : 20;
        }
        index = index + pageNo * pageSize
        let rowSelection = this.props.rowSelection;
        let selectedRowKeys = this.state.selectedRowKeys || [];
        if(rowSelection == 'checkbox'){
            let selectedIds = this.state.selectedIds || [];
            let selectedItem = this.state.selectedItem || {};
            const i = selectedRowKeys.indexOf(index);
            if (i == -1) {//避免重复添加
                selectedIds.push(record[this.props.selectedKey])
                selectedRowKeys.push(index);
                selectedItem=record;
            }else{
                selectedIds.splice(i,1);
                selectedRowKeys.splice(i,1);
                selectedItem={};
            }
     
            this.onSelectCallBack(selectedRowKeys,selectedItem || {},selectedIds);
        }else{
            let selectKey = [index];
           
            if (selectedRowKeys && selectedRowKeys[0] == index){
                this.onSelectCallBack([],{});
                return;
            }
            this.onSelectCallBack(selectKey,record || {});
        }
    };

    // 选择框变更
    onSelectChange = (selectedRowKeys, selectedRows) => {
      
        let selectedIds= [];
        selectedRows.forEach(element => {
            selectedIds.push(element[this.props.selectedKey])
        });
        let item = this.props.rowSelection !== 'checkbox'
            ? selectedRows[0] : selectedRows;
        this.onSelectCallBack(selectedRowKeys,item || {},selectedIds);
    };

    onSelectAll = (selected, selectedRows, changeRows) => {
        let selectedIds = [];
        let selectKey = [];
        if(selected){
            let data = this.state.dataSource || this.props.dataSource;
            data.forEach((item,i)=> {
                selectedIds.push(item[this.props.selectedKey]);
                selectKey.push(i);
            });
        }
        this.onSelectCallBack(selectKey,selectedRows || {},selectedIds);
    }

    onSelectCallBack = (selectedRowKeys = [], selectedItem = {},selectedIds = []) => {
        this.setState({
            selectedRowKeys,
            selectedItem,
            selectedIds,
        });
        this.props.updateSelectedItem(selectedRowKeys,selectedItem,selectedIds);
    };

    handleTableChange = (pagination, filters, sorter) => {
    }

    getOptions = () => {
        const { selectedRowKeys } = this.state;
        const rowSelection = {
            type: 'radio',
            selectedRowKeys,
            onChange: this.onSelectChange,
            onSelect:(record, selected, selectedRows)=>{
                
            },
            onSelectInvert:(selectedRows)=>{
                
            },
            onSelectAll:this.onSelectAll
        };
        let row_selection = this.props.rowSelection;
        // 当属性未false或者null时，说明没有单选或者复选列
        if(row_selection===false || row_selection === null
             || row_selection === undefined){
            row_selection = false;
        }else if(row_selection == 'checkbox'){
            //设置类型未复选框
            rowSelection.type = 'checkbox';
        }else{
            //默认未单选
            row_selection = 'radio';
        }
        let _this=this; 
        let pagination = this.props.pagination;
        let data = this.state.dataSource || this.props.dataSource;
        data = data || [];
        return <Table 
                    className="card-wrap page-table"
                    size='small'
                    bordered 
                    {...this.props}
                    columns={this.state.columns || this.props.columns}
                    dataSource={data}
                    scroll={this.state.scroll || this.props.scroll}
                    bodyStyle={
                        data.length > 0 ?
                        {height:this.state.scroll ? this.state.scroll.y : this.props.scroll.y}
                        : {}
                    }
                    rowSelection={row_selection?rowSelection:null}
                    pagination={this.props.noPagin ? false : {
                        onChange:(pageNo)=>{
                            // this.onSelectCallBack([],{},[]);
                            this.setState({pageNo})
                            pagination.onChange && pagination.onChange(pageNo)
                        },
                        current:this.state.pageNo || 1,
                        pageSize:pagination ? pagination.pageSize : 20,
                        total: pagination ? pagination.total : 20,
                        showTotal:()=>{
                            return `共${pagination ? pagination.total : 20}条`
                        },
                        showQuickJumper:{
                            goButton: <Button style={{marginLeft:15}} size='small'>确定</Button>
                        }
                    }}
                    onRow={(record,index) => ({
                        onClick: ()=>{
                            if(!row_selection){
                                return;
                            }
                            this.onRowClick(record,index)
                        },
                        onDoubleClick: ()=>{
                            this.onRowClick(record,index)
                            this.props.onDoubleClick&&this.props.onDoubleClick(record,index)
                        }
                    })}
                    rowClassName={(record, idx) => {
                        if(idx % 2 === 1)
                            return 'bg-row';
                    }}
                    onChange={this.handleTableChange}
                   
                />
    };
    render = () => {
        return (
            <div>
                {this.getOptions()}
            </div>
        )
    }
    
}
export default ETable
